<template>
  <Table ref="tableRef" :columns="columns" :data="loadData" :alert="false" bordered>
    <template #operator>
      <div class="table-search">
        <div>
          <span class="table-search-box">
            <a-input v-model:value="searchValue" placeholder="请输入名称关键字" style="width: 240px" allowClear>
              <template #prefix>
                <SvgIcon class="iconDef" :name="'search'" :color="'#d9d9d9'" width="16" height="16" />
              </template>
            </a-input>
          </span>
        </div>
        <div class="table-search-btn">
          <a-button class="actionBtn" type="primary" ghost @click="tableRef.refresh(true)">
            <SvgIcon class="iconDef" :name="'search'" :color="'#2590FF'" width="16" height="16" />
            查询
          </a-button>

          <a-button class="actionBtn" type="primary" ghost @click="refreshTable">
            <SvgIcon class="iconDef" :name="'refresh'" :color="'#2590FF'" width="16" height="16" />
            重置
          </a-button>
        </div>
      </div>
      <div style="margin-top: 16px">
        <a-button type="primary" @click="addTemplate">
          <PlusOutlined />
          新增模板
        </a-button>
      </div>
    </template>
    <template #bodyCell="{ column, record, index }">
      <template v-if="column.dataIndex === 'index'"> {{ index + 1 }} </template>
      <template v-if="column.dataIndex === 'componentType'"> {{ componentType[record.componentType] }} </template>
      <template v-if="column.dataIndex === 'action'">
        <div class="table-operation">
          <a @click="handelCopy(record)">复制</a>
          <a @click="handelDetial(record)">详情</a>
          <a @click="editTemplate(record)">编辑</a>
          <a @click="deleteTemplate(record)">删除</a>
        </div>
      </template>
    </template>
  </Table>
  <BasicModal
    ref="showActionModal"
    title="复制流水线模板"
    width="500px"
    @emit-callback-fn="modalCallbackFn($event)"
    :confirmLoading="copyTemplateLoading"
    okText="确认复制"
  >
    <template #content> <SchemaForm ref="formRef" /></template>
  </BasicModal>
</template>

<script setup lang="ts">
import { getPipelineTemplate, deletePipelineTemplate, copyPipelineTemplate } from '@/api/operationManagement';
import { useForm } from '@/components/SchemaForm/index';
import type { FormSchema } from '@/components/SchemaForm';
import { PlusOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { Modal } from 'ant-design-vue';
import { createVNode } from 'vue';
import { TypeEnumCode } from '@/enums/commonEnum';
import { formatToDatetime } from '@/utils/DateUtil';
const router = useRouter();
const columns = [
  { dataIndex: 'index', title: '序号', align: 'center', width: 60 },
  { dataIndex: 'name', title: '流水线模板名称', align: 'center', ellipsis: true },
  { dataIndex: 'componentType', title: '组件类型', align: 'center', ellipsis: true },
  { dataIndex: 'programLanguage', title: '编程语言', align: 'center', width: 300, ellipsis: true },
  { dataIndex: 'creator', title: '创建人', align: 'center', ellipsis: true },
  { dataIndex: 'createTime', title: '创建时间', align: 'center', ellipsis: true },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 180,
  },
];

const componentType: any = {
  1: TypeEnumCode.node,
  2: TypeEnumCode.java,
};

const searchValue = ref('');
const tableRef = ref<any>('');

const loadData = async (parameter: any) => {
  const parameObj = {
    currentPage: parameter.current,
    pageSize: parameter.size,
    condition: {
      condition: searchValue.value,
    },
  };
  const data = await getList(parameObj);
  return data;
};

const [SchemaForm, formRef] = useForm({
  schemas: [
    {
      field: 'templateName',
      label: '模板名称',
      labelWidth: 80,
      required: true,
      colProps: {
        span: 24,
      },
      component: 'Input',
    },
  ] as FormSchema[],
});

const showActionModal = ref<any>(null);
const copyTemplateLoading = ref<boolean>(false);
const modalCallbackFn = async (data: any) => {
  const fromData = formRef.getFieldsValue();
  copyTemplateLoading.value = true;
  const dataCopy = {
    pipelineTemplateUuid: data.propsData.uuid,
    newPipelineTemplateName: fromData.templateName,
  };
  await copyPipelineTemplate(dataCopy)
    .then(() => {
      message.success('复制成功');
      showActionModal.value.hideModal();
      tableRef.value.refresh(true);
    })
    .finally(() => {
      copyTemplateLoading.value = false;
    });
};

// 复制模板
const handelCopy = (record: any) => {
  nextTick(() => {
    formRef.setFieldsValue({
      templateName: `${formatToDatetime(new Date(), 'YYYYMMDDHHmmss')}${record.name}`,
    });
  });
  showActionModal.value.showModal(record);
};

//表格详情
const handelDetial = (record: any) => {
  router.push(`/system/pipelineTemplate/info/${record.uuid}`);
};

//添加
const addTemplate = () => {
  router.push(`/system/pipelineTemplate/add`);
};

//编辑
const editTemplate = (record: any) => {
  router.push(`/system/pipelineTemplate/edit/${record.uuid}`);
};

//删除流水线模板
const deleteTemplate = (record: any) => {
  Modal.confirm({
    title: '提示',
    icon: '',
    centered: true,
    content: createVNode('div', { style: 'color:black;' }, `确定要删除“流水线模板：${record.name}”这一项数据吗？`),
    async onOk() {
      await deletePipelineTemplate(record.uuid).then((res: any) => {
        message.success('删除成功');
        tableRef.value.refresh(true);
      });
    },
    onCancel() {},
    class: 'test',
  });
};

//刷新表格数据
const refreshTable = () => {
  searchValue.value = '';
  tableRef.value.refresh(true);
};

//获取表格数据
const getList = async (parameObj: OperationManagement.tableParamsList) => {
  return await getPipelineTemplate(parameObj).then((res: any) => {
    const data = {
      total: res.totalCount,
      current: res.currentPage,
      pageSize: res.pageSize,
      records: res.records,
    };
    return data;
  });
};
</script>

<style scoped lang="less">
.table-search {
  border-bottom: 1px solid #e7eff8;
  padding-bottom: 16px;
}
</style>
